package com.zhentao.service.impl;

import com.zhentao.common.DateUtils;
import com.zhentao.common.dtos.ResponseResult;
import com.zhentao.constants.UserThreadLocal;
import com.zhentao.service.CheckinsService;
import com.zhentao.service.coupons.CouponsFeignService;
import com.zhentao.user.domain.AppUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
* @author 86188
* @description 针对表【checkins】的数据库操作Service实现
* @createDate 2024-09-02 15:08:57
*/
@Service
@Slf4j
public class CheckinsServiceImpl implements CheckinsService{

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CouponsFeignService couponsFeignService;

    @Override
    public Boolean isLogin() {
        AppUser userInfo = UserThreadLocal.getUserInfo();
        if(userInfo == null){
            return false;
        }
        return true;
    }

    @Override
    public ResponseResult checkinsDays(Integer id, String  days) {
        if (isLogin()) {
            //转换日期
            Date date = DateUtils.stringToDate(days);
            //转换一个月的第几天
            int dayOfDate = DateUtils.getDayOfDate(date);
            String key = getKey(id, days);
            Boolean bit = redisTemplate.opsForValue().getBit(key, dayOfDate-1);
            if(bit){
                return ResponseResult.errorResult(400,"用户已经签到");
            }
            redisTemplate.opsForValue().setBit(key, dayOfDate-1, true);
            int i = checkinsList(key, dayOfDate);
            if(i==7){
                couponsFeignService.addCoupons(id);
                return ResponseResult.errorResult(200,"恭喜你，连续签到7天，获得100元代金券");
            }
            return ResponseResult.okResult(200,"本月连续签到"+i+"天");
        }
        else {
            return ResponseResult.errorResult(4000,"用户未登录");
        }


    }
//    键
    public String getKey(Integer id,String days){
        //转换日期
        Date date = DateUtils.stringToDate(days);
        //转换一个月的第几天
        int dayOfDate = DateUtils.getDayOfDate(date);
        //转换第年
        int yearOfDate = DateUtils.getYearOfDate(date);
        int monOfDate = DateUtils.getMonthOfDate(date);
        return "checkins:" + id + ":" + yearOfDate + ":" + monOfDate;
    }

    /**
     * 连续签到几天
     * @param key
     * @param dayOfMonth
     * @return
     */

    @Override
    public int checkinsList(String key,Integer dayOfMonth) {

        List<Long> result = redisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        .valueAt(0));
        log.info("查询数据:{}", result);
        if (result == null || result.isEmpty()) {
            return 0;
        }
        Long number = result.get(0);
        int count = 0;
        if (number == null || number == 0) {
            return 0;
        }
        while (true) {
            // 让这个数字与1做与运算，得到数字的最后一位bit，并判断这个bit是否为0
            if ((number & 1) == 0) {
                // 如果为0说明不是连续签到，直接终止
                break;
            } else {
                // 如果不为0，那就为1，说明有签到，继续下次循环，并且计数器加一
                count++;
            }
            // 把数字右移一位，抛弃最后一位的bit，继续下一个bit
            number = number >>> 1; // 也可以写成 number >>>= 1
        }
        System.out.println(count);
        return count;
    }

}




